package com.yiren.manager.ctrl.vip;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElderPayRecord;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrUserVipCard;
import com.yiren.entity.YrUserVipCardRecord;
import com.yiren.entity.YrUserVipCardRent;
import com.yiren.entity.YrVipCard;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.vip.YrUserVipCardForm;
import com.yiren.manager.form.vip.YrUserVipCardRecordForm;
import com.yiren.manager.form.vip.YrUserVipCardRentForm;
import com.yiren.manager.service.iface.cost.YrElderPayRecordService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRecordService;
import com.yiren.manager.service.iface.vip.YrUserVipCardRentService;
import com.yiren.manager.service.iface.vip.YrUserVipCardService;
import com.yiren.manager.service.iface.vip.YrVipCardService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("userVipCard")
@Controller
public class YrUserVipCardController extends GenericController<YrUserVipCardForm, YrUserVipCard> {

	@Autowired
	private YrUserVipCardService selfService;

	@Autowired
	private YrUserVipCardRentService userVipCardRentService;

	@Autowired
	private YrUserVipCardRecordService userVipCardRecordService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	@Autowired
	private YrElderPayRecordService elderPayRecordService;
	

	// 保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrUserVipCardForm> save(String data) throws SwallowException, MyException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
		HTTPResult<YrUserVipCardForm> result = new HTTPResult<YrUserVipCardForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrUserVipCardForm form = tool.mapper("userVipCard", YrUserVipCardForm.class);
		if (null == form) {
			throwExp("param.error");
		}

		if (null == form.getUserVipCardId() || form.getUserVipCardId().isEmpty()) {
			form.setUserVipCardId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			form.setUseStatus(0);
		} else {
			form.setUpdateTime(new Date());
		}
		if(!StringUtil.isEmpty(form.getCreateId())){
			YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
			if(null!=staffInfo){
				form.setCreator(staffInfo.getName());
			}
		}
		YrUserVipCard entity = ObjectUtils.objectToObject(form, YrUserVipCard.class);
		selfService.save(entity);
		List<YrUserVipCardForm> formList = new ArrayList<YrUserVipCardForm>();
		formList.add(form);
		result.setData(formList);

		return result;
	}

	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrUserVipCardForm> find(String searchVal) throws Exception {
		HTTPResult<YrUserVipCardForm> result = new HTTPResult<YrUserVipCardForm>();
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrUserVipCard> qr = selfService.find(YrUserVipCard.class, sqlWhere,
				new Object[] { searchVal, searchVal });

		List<YrUserVipCardForm> formList = new ArrayList<YrUserVipCardForm>();
		for (YrUserVipCard entity : qr.getResultList()) {
			YrUserVipCardForm form = toForm(entity);
			if(!StringUtil.isEmpty(form.getCreateId())){
				YrStaffInfo staffInfo = staffInfoService.findOne(form.getCreateId());
				if(null!=staffInfo){
					form.setCreator(staffInfo.getName());
				}
			}
			if(!StringUtil.isEmpty(form.getUpdateId())){
				YrStaffInfo staffInfo = staffInfoService.findOne(form.getUpdateId());
				if(null!=staffInfo){
					form.setMender(staffInfo.getName());
				}
			}
			sqlWhere = "user_vip_card_id=?1";
			QueryResult<YrUserVipCardRecord> qrUserVipCardRecord = userVipCardRecordService
					.find(YrUserVipCardRecord.class, sqlWhere, new Object[] { form.getUserVipCardId() });
			if (qrUserVipCardRecord.getTotalRecord() > 0) {
				form.setUserVipCardRecordForm(ObjectUtils.objectToObject(qrUserVipCardRecord.getResultList().get(0),
						YrUserVipCardRecordForm.class));
			}
			QueryResult<YrUserVipCardRent> qrUserVipCardRent = userVipCardRentService.find(YrUserVipCardRent.class,
					sqlWhere, new Object[] { form.getUserVipCardId() });
			List<YrUserVipCardRentForm> userVipCardRentForms = new ArrayList<YrUserVipCardRentForm>();
			for (YrUserVipCardRent userVipCardRent : qrUserVipCardRent.getResultList()) {
				userVipCardRentForms.add(ObjectUtils.objectToObject(userVipCardRent, YrUserVipCardRentForm.class));
			}
			form.setUserVipCardRentForms(userVipCardRentForms);
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findUserVipCardCostSumm")
	@ResponseBody
	public HTTPResult<YrUserVipCardForm> findUserVipCardCostSumm(String day) throws Exception{
		HTTPResult<YrUserVipCardForm> result = new HTTPResult<YrUserVipCardForm>();
		
		if(StringUtil.isEmpty(day)){
			throwExp("参数有误");
		}
		
		String sqlWhere = "pay_way=3 AND DATE_FORMAT(pay_date,'%Y-%m-%d')<=?1 OR "
				+ "(return_time is not null AND DATE_FORMAT(return_time,'%Y-%m-%d')<=?1)";
		
		QueryResult<YrElderPayRecord> qr = elderPayRecordService.find(YrElderPayRecord.class,sqlWhere, new Object[]{day});
		
		List<YrElderPayRecord> elderPayRecords = qr.getResultList();
		
		Map<String, List<YrElderPayRecord>> map = new HashMap<String,List<YrElderPayRecord>>();
		
		for(YrElderPayRecord elderPayRecord : elderPayRecords){
			List<YrElderPayRecord> list = null;
			if(map.containsKey(elderPayRecord.getRelationId())){
				list = map.get(elderPayRecord.getRelationId());
			}else {
				list = new ArrayList<YrElderPayRecord>();
			}
			list.add(elderPayRecord);
			map.put(elderPayRecord.getRelationId(), list);
		}
		List<YrUserVipCard> userVipCards = selfService.findAll();
		
		List<YrUserVipCardForm> userVipCardForms = new ArrayList<YrUserVipCardForm>();
		for(YrUserVipCard userVipCard : userVipCards){
			YrUserVipCardForm userVipCardForm = toForm(userVipCard);
			
			List<YrElderPayRecord> _list = map.get(userVipCard.getUserVipCardId());
			Float totalPay = 0F;
			if(null!=_list){
				for(YrElderPayRecord elderPayRecord : _list){
					if(elderPayRecord.getPayStatus()==3){//如果是已退费
						totalPay = totalPay-elderPayRecord.getReturnMoney();
					}else{
						totalPay = totalPay+elderPayRecord.getPayMoney();
					}
				}
			}
			userVipCardForm.setTotalPay(totalPay);
			userVipCardForms.add(userVipCardForm);
		}
		
//		List<YrVipCard> vipCards = vipCardService.findAll();
//		Map<String, YrVipCard> map = new HashMap<String, YrVipCard>();
//		for(YrVipCard vipCard : vipCards){
//			map.put(vipCard.getVipCardId(), vipCard);
//		}
//		
//		for(YrUserVipCardForm userVipCardForm : userVipCardForms){
//			userVipCardForm.setVipCardName(vipCardName);
//		}
		
		result.setData(userVipCardForms);
		return result;
	}

	@Override
	public YrUserVipCardForm toForm(YrUserVipCard e) throws Exception {
		YrUserVipCardForm form = ObjectUtils.objectToObject(e, YrUserVipCardForm.class);
		return form;
	}

	@Override
	public YrUserVipCard toEntity(YrUserVipCardForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
